package com.spdzen.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spdzen.service.SysRoleResourceService;
import com.spdzen.support.LogUtils;
import com.spdzen.support.SimpleStringUtils;
import com.spdzen.support.result.JsonResult;

@Controller
@RequestMapping("/admin/sysrole")
public class SysRoleResourceAdminController {
	@Resource
	private SysRoleResourceService sysRoleResourceService;
	
	@RequestMapping("/queryResourceTree.do")
	@ResponseBody
	public JsonResult queryTree(Long sysRoleId) {
		if(sysRoleId == null || sysRoleId.longValue() < 1) {
			return JsonResult.errorParameter();
		}
		
		try {
			return JsonResult.success(sysRoleResourceService.selectTree(sysRoleId));
		} catch (Exception e) {
			LogUtils.getLogger().error(sysRoleId.toString(), e);
			return JsonResult.error();
		}
	}
	
	@RequestMapping("/bindResources.do")
	@ResponseBody
	public JsonResult bindResources(Long sysRoleId, String sysResourceIds) {
		if(sysRoleId == null || sysRoleId.longValue() < 1) {
			return JsonResult.errorParameter();
		}
		
		List<Long> rids = SimpleStringUtils.toLongList(sysResourceIds, ",");
		
		List<Long> crids = new ArrayList<>();
		for(Long id : rids) {
			if(id.longValue() > 0) {
				crids.add(id);
			}
		}
		
		try {
			sysRoleResourceService.bindResources(sysRoleId, crids);
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.getLogger().error(sysRoleId.toString(), e);
			return JsonResult.error();
		}
	}
}
